package com.bupt.cad.utils;

import org.jumpmind.symmetric.csv.CsvReader;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CsvUtil {
    public static String specialUnicode(String str){
        if (str.startsWith("\uFEFF")){
            str = str.replace("\uFEFF", "");
        }else if (str.endsWith("\uFEFF")){
            str = str.replace("\uFEFF","");
        }
        return str;
    }
    public static List<Map<String,Object>> Csv2Json(MultipartFile multipartFile){
        InputStream inputStream = null;
        try {
            inputStream = multipartFile.getInputStream();

            CsvReader csvReader =new CsvReader(inputStream,',', Charset.forName("utf-8"));
            List<Map<String,Object>> list = new ArrayList<>();
            String[] headers=null;
            if(csvReader.readHeaders()){
                headers= csvReader.getHeaders();
                headers[0] = specialUnicode(headers[0]);

            }
            while(csvReader.readRecord()){
                Map<String,Object> data = new HashMap<>();
                data.put(headers[0],csvReader.get(0));
                data.put(headers[1],csvReader.get(1));
                list.add(data);
            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
